/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.fedoraaccess.cli;

import cz.mzk.kramerius.fedoraaccess.FedoraConnector;
import cz.mzk.kramerius.fedoraaccess.FedoraServer;
import cz.mzk.kramerius.fedoraaccess.rest.RESTConnector;
import cz.mzk.rehan.commons.CommandLineInterface;
import cz.mzk.rehan.commons.PropertyLoader;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class Main {

    private static final DefinedOptions DEFINED_OPTIONS = new DefinedOptions();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String[] testArgs = new String[]{
            "-p", "/home/rehan/rukopisy/mk.properties",
            "-a", "purgeObjects",
            "-o", "/home/rehan/tmp/pidsToRemove.txt"
        };
        //args = testArgs;
        try {
            CommandLineInterface cli = new CommandLineInterface(args, DEFINED_OPTIONS);
            PropertyLoader loader = new PropertyLoader(cli.getStringValueOrNull(DEFINED_OPTIONS.PROPERTIES_FILE));
            Action action = determineAction(cli, loader);
            action.run();

        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }
    }

    private static Action determineAction(CommandLineInterface cli, PropertyLoader propertiesLoader) throws Exception {
        String action = cli.getStringValueOrNull(DEFINED_OPTIONS.ACTION);
        FedoraConnector fedora = initFedoraConnector(propertiesLoader);
        if ("purgeObjects".equals(action)) {
            File objectsFile = new File(cli.getStringValueOrNull(DEFINED_OPTIONS.OBJECTS_FILE));
            return new PurgePidsAction(fedora, objectsFile);
        } else if ("test".equals(action)) {
            return new TestAction(fedora);
        } else {
            throw new Exception("No such action " + action);
        }
    }

    private static FedoraConnector initFedoraConnector(PropertyLoader propertiesLoader) throws IOException {
        FedoraServer fedora = new FedoraServer(propertiesLoader);
        return new RESTConnector(fedora);
    }
}
